import getPosition from './js/getPosition'
import Core from './js/core'
import Axises from './js/Axises'
import { EventBus } from '../../common/EventBus'

function dynamicObject(viewer, pointMark) {
  this._viewer = viewer;
  // this._cesium = cesium;
  this._core = new Core();
  this._getPosition = new getPosition(this._viewer, Cesium);
  this._entityFly = null;
  this._axises = new Axises({}, viewer);

  this.tooltip = this._core.CreateTooltip();

  this._nodes = null
  this._viewEvents = []; // 存储视角
  this._isInStayPhase = false; // 标识是否处于停留阶段

  this._pointIcon = pointMark ? pointMark : require('@/assets/img/mark.png')
}

var entityFly = null;
var entityModel = null;
//var start;
var fun = null;
var entityhd = {
  start: null,
  time: null,
  longitude: 0,
  latitude: 0,
  cameraHeight: 10,
  //timedifference: null,
  speed: 50.5,
  multiplier: 1,
  position: 0,
  mode: 0,
};
var velocityVector, velocityVectorProperty, velocityOrientationProperty, totalTime;
var AngleProperty, property, realSpeed;
var wheelAngle = 0;
var labelEntity = []
var maxNum = 0

dynamicObject.prototype.changePointAttribute = function (attribute) {
  for (let i of labelEntity) {
    if (i.properties.Number._value == attribute.Number) {
      i.properties = attribute
    }
  }


}
dynamicObject.prototype.exitAttributeEdit = function () {
  if (this.handler) {
    this.handler.destroy()
    this.handler = undefined
  }
}
dynamicObject.prototype.EditAttribute = function (getPointAttribute, callback) {
  var _this = this
  var handler = this.handler = new Cesium.ScreenSpaceEventHandler(_this._viewer.scene.canvas)
  handler.setInputAction((movement) => {
    var pointEntity = _this._viewer.scene.pick(movement.position)
    let nodeProperty
    if (pointEntity && pointEntity.id && pointEntity.id instanceof Cesium.Entity) {
      nodeProperty = {
        Number: pointEntity.id.properties.Number._value,
        hoveringtime: pointEntity.id.properties.hoveringtime._value,
        angle: pointEntity.id.properties.angle._value,
        flightHs: pointEntity.id.properties.flightHs._value,
        speed: pointEntity.id.properties.speed._value,
        postureList: pointEntity.id.properties.postureList._value
      }
      getPointAttribute(nodeProperty)
      callback(pointEntity.id)
    }
    callback()
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
  handler.setInputAction(movement => {
    _this.tooltip.showAt(movement.endPosition, '左击选中节点,右击结束')
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)
  handler.setInputAction(movement => {
    end()
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)

  function end() {
    EventBus.$emit('changeIsEditPointAtr', false)
    _this.tooltip.show(false)
    _this.exitPointEdit()
  }
}

//新增节点
dynamicObject.prototype.AddPosition = function (getpoint) {
  var _this = this
  var handler = this.handler = new Cesium.ScreenSpaceEventHandler(_this._viewer.scene.canvas)
  handler.setInputAction((movement) => {
    var cartesian = _this._getPosition.getMousePosition(movement);
    let addPoint = this._core.getClosetPointOfpolyline(cartesian, _this.ploylinejl.positions)
    maxNum = addPoint.index + 2

    labelEntity.splice(addPoint.index + 1, 0, _this._viewer.entities.add({
      position: addPoint.position,
      point: {},
      label: {
        text: maxNum.toString(),
        pixelOffset: new Cesium.Cartesian2(20, -20),
        font: "16px sans-serif"
      },
      billboard: {
        image: _this._pointIcon,
        width: 28,
        height: 28,
        pixelOffset: new Cesium.Cartesian2(0, -20)

      },
      properties: {
        Number: maxNum.toString(),
        hoveringtime: 0,
        angle: 0,
        flightHs: 0,
        speed: 0,
        pitch: 0,
        // declineSpeed: 0,
        postureList: []
      }


    }))

    _this.ploylinejl.positions.splice(addPoint.index + 1, 0, addPoint.position)
    _this.setItemPosition(_this.ploylinejl.positions)
    this.adjustLabel()
    getpoint(addPoint, maxNum)
    handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK)

}
dynamicObject.prototype.adjustLabel = function () {
  for (let i = 0; i < labelEntity.length; i++) {
    const entity = labelEntity[i];
    entity.label.text = (i + 1).toString()
    entity.properties.Number._value = (i + 1).toString()
  }
}
dynamicObject.prototype.adjustLabelHidden = function (checked) {
  for (let i = 0; i < labelEntity.length; i++) {
    const entity = labelEntity[i];
    entity.show = checked
  }
}
dynamicObject.prototype.EditPosition = function (getPoint, callback) {
  var _this = this
  var handler = this.handler = new Cesium.ScreenSpaceEventHandler(_this._viewer.scene.canvas)
  var pointEntity
  let selectedPosition

  handler.setInputAction((movement) => {
    pointEntity = _this._viewer.scene.pick(movement.position)
    if (pointEntity && pointEntity.id && pointEntity.id instanceof Cesium.Entity && pointEntity.id.show) {
      _this._axises.prepareDragging(pointEntity);
      callback(pointEntity)
    } else if (pointEntity && pointEntity.id && _this._axises.isMe(pointEntity.id)) {
      _this._axises.initDraging(movement, pointEntity.id);
    } else {
      _this._axises.hiddenDragging(false)
    }



    function gg(e) {
      var flagName = getFlagCode(e.code)
      let cartographic = Cesium.Cartographic.fromCartesian(selectedPosition)
      let longitude = Cesium.Math.toDegrees(cartographic.longitude)
      let latitude = Cesium.Math.toDegrees(cartographic.latitude)
      let height = cartographic.height
      let newPosition
      if (flagName == "arrowup") {
        height = height + 1
        newPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
        pointEntity.id.position = newPosition
      } else if (flagName == 'arrowdown') {
        height = height - 1
        newPosition = Cesium.Cartesian3.fromDegrees(longitude, latitude, height)
        pointEntity.id.position = newPosition
      }
      selectedPosition = pointEntity.id.position._value
      let index = labelEntity.indexOf(pointEntity.id)
      _this.ploylinejl.positions[index] = pointEntity.id.position._value
      _this.setItemPosition(_this.ploylinejl.positions)
      getPoint(index, newPosition, pointEntity.id.label.text._value)

    }
    // document.addEventListener('keydown', gg)

    function getFlagCode(e) {
      let flagName
      switch (e) {
        case 'ArrowUp':
          flagName = 'arrowup'
          break
        case 'ArrowDown':
          flagName = "arrowdown"
          break

      }
      return flagName

    }

    handler.setInputAction((movement) => {
      if (_this._axises.dragging(movement)) {
        var curPos = _this._axises.getPos();
        _this._axises._entity.id.position = curPos;
        let index = labelEntity.indexOf(_this._axises._entity.id)
        _this.ploylinejl.positions[index] = curPos
        _this.setItemPosition(_this.ploylinejl.positions)

        getPoint(index, curPos, _this._axises._entity.id.label.text._value)
      }

    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

    handler.setInputAction((movement) => {
      handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE)
      handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_UP)
      // document.removeEventListener('keydown', gg)

      _this._axises.stopDragging();

    }, Cesium.ScreenSpaceEventType.LEFT_UP)

    handler.setInputAction(() => {

      handler.removeInputAction(Cesium.ScreenSpaceEventType.RIGHT_UP);

      _this._axises.finishDragging();
      EventBus.$emit("changeIsEditPoint", false)
      
      //_this.exitPointEdit()

    }, Cesium.ScreenSpaceEventType.RIGHT_UP)

  }, Cesium.ScreenSpaceEventType.LEFT_DOWN)

  handler.setInputAction((movement) => {
    _this.tooltip.showAt(movement.endPosition, '左键按下移动,右键结束')
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

  handler.setInputAction(event => {
    end()
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)


  function end() {
    _this.tooltip.show(false)
    _this._axises.stopDragging()
    EventBus.$emit('changeIsEditPoint', false)
    _this.exitPointEdit()
  }
}

dynamicObject.prototype.exitPointEdit = function () {
  if (this.handler) {
    this.handler.destroy()
    this.handler = undefined
  }
}

dynamicObject.prototype.executeFlycesium = function (method, getPosition) {
  var _this = this;
  var PolyLinePrimitive = (function () {
    function execute(positions) {
      this.options = {
        polyline: {
          show: true,
          positions: [],
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.1,
            color: Cesium.Color.YELLOW
          }),
          width: 10,
          // clampToGround: true,
        }
      };
      this.positions = positions;
      this._init();
    }

    execute.prototype._init = function () {
      var _self = this;
      var _update = function () {
        return _self.positions;
      };
      //实时更新polyline.positions
      this.options.polyline.positions = new Cesium.CallbackProperty(_update, false);
      this.flycesium = _this._viewer.entities.add(this.options);
      _this.item = this.flycesium;
    }
    return execute
  })()
  var handler = this.handler = new Cesium.ScreenSpaceEventHandler(_this._viewer.scene.canvas)
  var positions = [];
  var distance = 0;
  var poly = undefined;

  var ploylinejl = {
    polyline: {},
    cameraRoll: null,
    cameraPitch: null,
    cameraPosition: null,
    cameraHeading: null,
    positions: [],
    distance: [],
    Totaltime: ""
  }
  handler.setInputAction(function (movement) {
    var cartesian = _this._getPosition.getMousePosition(movement);
    if (_this._core.getBrowser().pc === 'pc' && positions.length == 0) {
      positions.push(cartesian.clone());
    }
    positions.push(cartesian);
    maxNum = maxNum + 1
    let properties = {
      Number: maxNum.toString(),
      hoveringtime: 0,
      angle: 0,
      flightHs: 0,
      speed: 0,
      pitch: 0,
      // declineSpeed: 0,
      postureList: []
    }
    labelEntity.push(_this._viewer.entities.add({
      position: cartesian,
      point: {

      },
      label: {
        text: maxNum.toString(),
        pixelOffset: new Cesium.Cartesian2(20, -20),
        font: "16px sans-serif"
      },
      billboard: {
        image: _this._pointIcon,
        width: 28,
        height: 28,
        pixelOffset: new Cesium.Cartesian2(0, -20)

      },
      properties: properties

    }))
    if (positions.length >= 2) {
      if (!Cesium.defined(poly)) {
        poly = new PolyLinePrimitive(positions);
      }
      distance = _this._core.getSpaceDistancem(positions, Cesium);
    }
    getPosition(cartesian, maxNum, properties)
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

  handler.setInputAction(function (movement) {
    var cartesian = _this._getPosition.getMousePosition(movement);
    _this.tooltip.showAt(movement.endPosition, "点击绘制点");
    if (positions.length >= 2) {
      _this.tooltip.showAt(movement.endPosition, "点击绘制点,右击结束");
      if (!Cesium.defined(poly)) {
        poly = new PolyLinePrimitive(positions);

      } else {
        if (cartesian) {
          positions.pop();
          positions.push(cartesian);
        }
      }
      distance = _this._core.getSpaceDistancem(positions, Cesium);
    }
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE)

  //单击鼠标右键结束画线
  handler.setInputAction(function (movement) {
    positions.pop();
    _this.end();
  }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);

  this.end = function (type) {
    handler.destroy();
    _this.end = undefined
    this.tooltip.show(false);
    // _this._viewer.entities.remove(_this.item)

    if (type === 'cancel' || positions.length < 2) {
      return;
    }
    distance = _this._core.getSpaceDistancem(positions, Cesium)

    ploylinejl.polyline = poly;
    ploylinejl.positions = positions;
    ploylinejl.distance = parseFloat(distance);
    //转化成浏览对象
    _this.setFlycesium(ploylinejl, function (flyceium) {
      _this.flyceium = flyceium;
      _this.ploylinejl = ploylinejl;
      if (typeof method == 'function') {
        method(flyceium);
      }
    });
  }
}
dynamicObject.prototype.executeFlycesium_getPath = function (method, position, point) {
  var _this = this;
  var PolyLinePrimitive = (function () {
    function execute() {
      this.options = {
        polyline: {
          show: true,
          positions: position,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.1,
            color: Cesium.Color.YELLOW
          }),
          width: 10,
          // clampToGround: true,
        }
      };
      this.positions = positions;
      this._init();
    }

    execute.prototype._init = function () {
      var _self = this;
      var _update = function () {
        return _self.positions;
      };
      //实时更新polyline.positions
      this.options.polyline.positions = new Cesium.CallbackProperty(_update, false);
      this.flycesium = _this._viewer.entities.add(this.options);
      _this.item = this.flycesium;
      point.forEach((item) => {
        if (maxNum < item.No) {
          maxNum = item.No
        }
        labelEntity.push(_this._viewer.entities.add({
          position: new Cesium.Cartesian3.fromDegrees(parseFloat(item.longitude), parseFloat(item.latitude), parseFloat(item.height)),
          point: {

          },
          label: {
            text: item.No.toString(),
            pixelOffset: new Cesium.Cartesian2(20, -20),
            font: "16px sans-serif"
          },
          billboard: {
            image: _this._pointIcon,
            width: 28,
            height: 28,
            pixelOffset: new Cesium.Cartesian2(0, -20)

          },
          // properties: {
          //   Number: maxNum.toString(),
          //   hoveringtime: 0,
          //   angle: 0,
          //   postureList: []
          // }

        }))
      })

    }
    return execute
  })()
  var positions = position;
  var distance = 0;
  var poly = new PolyLinePrimitive(positions);

  var ploylinejl = {
    polyline: {},
    cameraRoll: null,
    cameraPitch: null,
    cameraPosition: null,
    cameraHeading: null,
    positions: [],
    distance: [],
    Totaltime: ""
  }

  if (positions.length < 2) {
    return;
  }
  distance = _this._core.getSpaceDistancem(positions, Cesium)

  ploylinejl.polyline = poly;
  ploylinejl.positions = positions;
  ploylinejl.distance = parseFloat(distance);
  //转化成浏览对象
  _this.setFlycesium(ploylinejl, function (flyceium) {
    _this.flyceium = flyceium;
    _this.ploylinejl = ploylinejl;
    if (typeof method == 'function') {
      method(flyceium);
    }
  });

}
/**
 * 获取路径数据
 * @param {Array<Degrees|Number>} degreesArr 坐标串
 * @param {*} callback 回调函数
 */
dynamicObject.prototype.getFlyData = function (degreesArr, callback) {
  let positions = [];
  if (typeof degreesArr[0] === 'object') {
    degreesArr.forEach(item => {
      positions.push(Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.height));
    });
  } else if (typeof degreesArr[0] === 'number') {
    positions = Cesium.Cartesian3.fromDegreesArrayHeights(degreesArr);
  }
  let distance = this._core.getSpaceDistancem(positions, Cesium);
  let data = this.setFlycesium({
    positions,
    distance
  }, callback);
  return data;
}

/**
 * 设置获取浏览对象
 */
dynamicObject.prototype.setFlycesium = function (drawHelper, callback) {
  var _this = this;
  var coordinates = [];
  for (var i = 0; i < drawHelper.positions.length; i++) {
    var cartographic = Cesium.Cartographic.fromCartesian(drawHelper.positions[i]); //世界坐标转地理坐标（弧度）
    var point = [cartographic.longitude / Math.PI * 180, cartographic.latitude / Math.PI * 180, cartographic.height]; //地理坐标（弧度）转经纬度坐标
    //console.log(point);
    coordinates.push(point);
  }

  var time;
  time = (drawHelper.distance / 15).toFixed(1)

  var pathsData = {
    id: _this._core.getuid(),
    name: '新建路线',
    distance: drawHelper.distance,
    showPoint: false,
    showLine: true,
    showModel: true,
    isLoop: false,
    Totaltime: Math.round(time),
    speed: 50.5,
    height: 10,
    perPositionHeight: true,
    pitch: -20,
    range: 100,
    mode: 0,
    url: "",
    geojson: {
      // orientation: {heading: heading, pitch: pitch, roll: roll},
      // position: position,
      geometry: {
        type: "LineString",
        coordinates: coordinates
      }
    }
  }
  callback && callback(pathsData);
  return pathsData
}
/**
 * 开始浏览
 */
dynamicObject.prototype.Start = function (data, url, funs) {
  var _this = this;
  data.geojson;
  if (!data.Totaltime) {
    data.Totaltime = 3000;
  }
  if (_this._entityFly) {
    _this.exit();
  }
  fun = funs;
  setTimeout(function () {
    _this.executeFly3D(data, url);
    _this.addTickListener()
  }, 200);
  return this;
}

/**
 * 播放路径动画
 * @param {Object} data 数据
 * @param {Object} data.geojson 路线数据
 * @param {Number} [data.lineHeight] 路线高度，默认贴地
 * @param {Number} [data.perPositionHeight=false] 是否使用每个位置的高度
 * @param {Boolean} [data.isLoop=false] 是否循环播放
 * @param {String} [url] 模型路径
 */

dynamicObject.prototype.executeFly3D = function (data, url) {
  var _this = this
  // _this._viewer.entities.remove(_this.item)
  if (_this.item) {
    _this.item.show = false
  }


  var pathsData = data.geojson
  velocityVector = new Cesium.Cartesian3()
  AngleProperty = new Cesium.SampledProperty(Number)
  realSpeed = new Cesium.SampledProperty(Number)
  property = new Cesium.SampledPositionProperty()

  if (pathsData && pathsData.geometry) {
    var positionA = pathsData.geometry.coordinates
    var position = []
    var position1 = []
    if (positionA.length > 0) {
      for (var i = 0; i < positionA.length; i++) {
        var x = positionA[i][0];
        var y = positionA[i][1];
        var z = positionA[i][2];
        data.lineHeight !== undefined && !data.perPositionHeight && (z = data.lineHeight);
        position1.push(x, y, z);
        position.push({
          x: x,
          y: y,
          z: z
        });
      }
    } else {
      return;
    }
    var _position = _this.createSampledPosition(data.positionData, position)

    _this._viewer.clock.clockRange = data.isLoop ? Cesium.ClockRange.LOOP_STOP : Cesium.ClockRange.CLAMPED //Loop at the end
    _this._viewer.clock.multiplier = data.multiplier || 1
    _this._viewer.clock.canAnimate = false
    _this._viewer.clock.shouldAnimate = true //设置时间轴动态效果
    entityhd.distance = data.distance
    entityhd.cameraHeight = this._core.defaultValue(data.height, 10)
    entityhd.lineHeight = data.lineHeight
    entityhd.perPositionHeight = data.perPositionHeight
    entityhd.pitch = data.pitch
    entityhd.range = data.range
    entityhd.speed = data.speed || 15
    entityhd.Totaltime = totalTime //data.distance/data.speed

    entityhd.start = Cesium.JulianDate.fromDate(new Date())
    entityhd.stop = Cesium.JulianDate.addSeconds(entityhd.start, entityhd.Totaltime, new Cesium.JulianDate())

    _this._viewer.clock.startTime = entityhd.start.clone()
    _this._viewer.clock.stopTime = entityhd.stop.clone()
    _this._viewer.clock.currentTime = entityhd.start.clone()

    // var _position = _this.computeCirclularFlight(position);

    entityhd.position = _position;
    entityhd.degrees = position;
    velocityOrientationProperty = new Cesium.VelocityOrientationProperty(_position)

    var mode = {}
    if (url !== "") {
      mode = {
        show: Cesium.defaultValue(data.showModel, true),
        scale: Cesium.defaultValue(data.modelScale, 0.1),
        uri: url,
        minimumPixelSize: 32
      };
    } else {
      mode = {
        show: Cesium.defaultValue(data.showModel, true),
        scale: Cesium.defaultValue(data.modelScale, 1)
      };
    }
    if (data.modelData) {
      mode = _this._core.extend(mode, data.modelData)
    }
    changeFlyView = function () {

    }
    entityFly = _this._viewer.entities.add({
      //Set the entity availability to the same interval as the simulation time.
      availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
        start: entityhd.start,
        stop: entityhd.stop
      })]),
      position: _position,
      //Show the path as a pink line sampled in 1 second increments.
      polyline: {
        clampToGround: entityhd.lineHeight === undefined && !entityhd.perPositionHeight,
        positions: Cesium.Cartesian3.fromDegreesArrayHeights(position1),
        show: Cesium.defaultValue(data.showLine, true),
        material: new Cesium.PolylineGlowMaterialProperty({
          glowPower: 0.1,
          color: Cesium.Color.YELLOW
        }),
        width: 10
      },
      label: {
        text: new Cesium.CallbackProperty(updateSpeedLabel, false),
        font: '20px sans-serif',
        showBackground: false,
        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0.0, 100.0),
        eyeOffset: new Cesium.Cartesian3(0, 3.5, 0)
      }
    })

    entityModel = _this._viewer.entities.add({
      availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
        start: entityhd.start,
        stop: entityhd.stop
      })]),
      position: _position,
      orientation: new Cesium.CallbackProperty(function (time, result) {
        const orientations = velocityOrientationProperty.getValue(time, result)
        const position = entityModel.position.getValue(time)
        if (!orientations) return //停留
        let Matrix3 = Cesium.Matrix3.fromQuaternion(orientations);
        let Matrix4 = Cesium.Matrix4.fromRotationTranslation(Matrix3, position);
        const euler = Cesium.Transforms.fixedFrameToHeadingPitchRoll(Matrix4);
        const hpr = new Cesium.HeadingPitchRoll(euler.heading, Cesium.Math.toRadians(0), 0)
        return Cesium.Transforms.headingPitchRollQuaternion(position, hpr)
      }, false), //velocityOrientationProperty
      point: {
        show: Cesium.defaultValue(data.showPoint, false),
        color: Cesium.Color.RED,
        outlineColor: Cesium.Color.WHITE,
        outlineWidth: 2,
        pixelSize: 10,
      },
      model: mode,
      billboard: data.image,
      viewFrom: data.viewFrom || new Cesium.Cartesian3(500.0, 500.0, 500.0)
    })

    entitymodels = entityFly
    _this._viewer.trackedEntity = entityModel
    _this._entityFly = entityFly
    entityhd.mode = data.mode
    data.mode && _this.changeFlyMode(data.mode)
  } else {
    return;
  }

  function updateSpeedLabel(time, result) {
    if (_this._viewer.clock.clockRange !== 2 && Cesium.JulianDate.equals(_this._viewer.clock.currentTime, _this._viewer.clock.stopTime)) {
      entityFly.label.text = ''
      //已漫游时间
      entityhd.time = entityhd.Totaltime
      //已漫游比例
      entityhd.ratio = 1.0
      //已漫游距离
      entityhd.distanceTraveled = entityhd.distance

      _this.exit()
      if (fun != null && typeof fun === 'function') {
        fun(entityhd, 'end');
      }
      changeFlyView = function () {

      };
      return;
    }
    try {
      var position = entitymodels.position.getValue(_this._viewer.clock.currentTime);
      var cartographic = Cesium.Cartographic.fromCartesian(position);
      //经度
      entityhd.longitude = Cesium.Math.toDegrees(cartographic.longitude);
      //纬度
      entityhd.latitude = Cesium.Math.toDegrees(cartographic.latitude);
      if (entityhd.lineHeight === undefined && !entityhd.perPositionHeight) {
        let height1 = _this._viewer.scene.sampleHeight(cartographic, [entityModel, entitymodels]);
        let height2 = _this._viewer.scene.globe.getHeight(cartographic);
        entityModel.position = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height2 > height1 ? height2 : height1);
      }
    } catch (ex) {}
    try {
      changeFlyView(time);
      //已漫游时间
      entityhd.time = Cesium.JulianDate.secondsDifference(time, entityhd.start);
      //已漫游比例
      entityhd.ratio = entityhd.time / entityhd.Totaltime;
      //已漫游距离
      entityhd.distanceTraveled = entityhd.ratio * entityhd.distance;
      //运行速度
      entityhd.speed = realSpeed.getValue(time);
      //漫游高程
      entityhd.height = _this._viewer.scene.globe.getHeight(cartographic) > cartographic.height ? _this._viewer.scene.globe.getHeight(cartographic) + entityhd.cameraHeight : cartographic.height + entityhd.cameraHeight;
      //地面高程
      entityhd.globeHeight = _this._viewer.scene.globe.getHeight(cartographic);
      entityModel.position = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
      if (fun != null && typeof fun === 'function') {
        fun(entityhd);
      }
    } catch (ex) {}
    return ""
  }
}

//添加时间位置样本
dynamicObject.prototype.createSampledPosition = function (positionData, positionss) {
  const nodes = this.getNodes(positionData)
  totalTime = this.calculateTotalTime(nodes);
  this._viewEvents = []
  velocityVectorProperty = new Cesium.VelocityVectorProperty(property, false);
  const startTime = Cesium.JulianDate.fromDate(new Date());

  let currentTime = Cesium.JulianDate.clone(startTime);
  let currentPosition = nodes[0].position;

  // 处理首节点停留
  if (nodes[0].stayDuration > 0) {
    const stayStartTime = Cesium.JulianDate.clone(currentTime)
    const stayEndTime = Cesium.JulianDate.addSeconds(currentTime, nodes[0].stayDuration, new Cesium.JulianDate());
    const adjustedHeading = this.calculateAngle(nodes[0], nodes[1])
    // 添加停留样本
    let t = 0;
    while (t <= nodes[0].stayDuration) {
      const sampleTime = Cesium.JulianDate.addSeconds(currentTime, t, new Cesium.JulianDate());
      property.addSample(sampleTime, currentPosition);
      // 添加停留期间的角度采样（保持初始角度）
      AngleProperty.addSample(sampleTime, adjustedHeading);
      realSpeed.addSample(sampleTime, 0)
      t += 0.1; // 100ms间隔
    }

    currentTime = stayEndTime;

    //添加时间
    nodes[0].stayStartTime = stayStartTime; //使用停留开始时间
    nodes[0].stayEndTime = stayEndTime;
    // 处理首节点的视角事件
    nodes[0].views.forEach((view) => {
      const eventTime = Cesium.JulianDate.addSeconds(stayStartTime, view.time, new Cesium.JulianDate());
      this._viewEvents.push({
        duration: nodes[0].stayDuration,
        stayTime: view.time,
        time: eventTime,
        view: view.view,
        triggered: false
      });
    });
  } else {
    property.addSample(currentTime, currentPosition);
  }

  for (let i = 0; i < nodes.length - 1; i++) {
    const currentNode = nodes[i];
    const nextNode = nodes[i + 1];

    const adjustedHeading = this.calculateAngle(currentNode, nextNode)

    // 计算飞行时间
    const distance = this._core.getSpaceDistancem([currentNode.position, nextNode.position], Cesium) //Cesium.Cartesian3.distance();
    const flightSeconds = distance / currentNode.speedToNext;
    // console.log('飞行时间：', flightSeconds);

    // 添加飞行路径样本
    const flightEndTime = Cesium.JulianDate.addSeconds(currentTime, flightSeconds, new Cesium.JulianDate());

    // 添加中间采样点
    let t = 0;
    while (t < flightSeconds) {
      const progress = t / flightSeconds;
      const position = Cesium.Cartesian3.lerp(
        currentNode.position,
        nextNode.position,
        progress,
        new Cesium.Cartesian3()
      );
      const sampleTime = Cesium.JulianDate.addSeconds(currentTime, t, new Cesium.JulianDate());
      property.addSample(sampleTime, position);
      AngleProperty.addSample(sampleTime, adjustedHeading); // 关键角度插值
      realSpeed.addSample(sampleTime, currentNode.speedToNext)
      t += 0.1;
    }

    // 添加最终位置
    property.addSample(flightEndTime, nextNode.position);
    AngleProperty.addSample(flightEndTime, adjustedHeading);
    realSpeed.addSample(flightEndTime, currentNode.speedToNext)
    // 更新当前时间基准
    currentTime = flightEndTime
    // 处理停留时间（包含末节点）
    if (nextNode.stayDuration > 0) {
      const stayEndTime = Cesium.JulianDate.addSeconds(flightEndTime, nextNode.stayDuration, new Cesium.JulianDate());

      // 保持航段终点角度
      let stayT = 0;
      while (stayT <= nextNode.stayDuration) {
        const sampleTime = Cesium.JulianDate.addSeconds(flightEndTime, stayT, new Cesium.JulianDate());
        AngleProperty.addSample(sampleTime, adjustedHeading); // 保持终点角度
        realSpeed.addSample(sampleTime, 0)
        stayT += 0.1;
      }

      property.addSample(stayEndTime, nextNode.position);

      currentTime = stayEndTime;

      nextNode.stayStartTime = Cesium.JulianDate.clone(flightEndTime);
      nextNode.stayEndTime = Cesium.JulianDate.addSeconds(flightEndTime, nextNode.stayDuration, new Cesium.JulianDate());
      nextNode.views.forEach((view) => {
        const eventTime = Cesium.JulianDate.addSeconds(nextNode.stayStartTime, view.time, new Cesium.JulianDate());
        this._viewEvents.push({
          duration: nextNode.stayDuration,
          stayTime: view.time,
          time: eventTime,
          view: view.view,
          triggered: false,
          properties: nextNode
        });
      });
    } else {
      currentTime = flightEndTime;
    }
  }
  this._nodes = nodes
  return property;
}

/**
 * 获取特殊格式的节点
 * @param {*} data 含有节点属性的数据
 * @returns 特殊格式的节点
 */
dynamicObject.prototype.getNodes = function (data) {
  let nodes = []
  for (let i = 0; i < data.length; i++) {
    const psData = data[i];
    const speed = psData.properties.speed == 0 ? 15 : psData.properties.speed
    const lon = Number(psData.longitude)
    const lat = Number(psData.latitude)
    const height = Number(psData.height)
    const time = Number(psData.properties.hoveringtime)
    const views = psData.properties.postureList
    const nodeData = new this.flightNode(lon, lat, height, Number(speed), time, views)
    nodes.push(nodeData)
  }
  return nodes
}

/**
 * 节点处理
 * @param {*} longitude 
 * @param {*} latitude 
 * @param {*} height 节点高度
 * @param {*} speedToNext 节点速度
 * @param {*} stayDuration 悬停时间
 * @param {*} viewArr 视角
 */
dynamicObject.prototype.flightNode = function (longitude, latitude, height, speedToNext, stayDuration, viewArr) {
  this.position = Cesium.Cartesian3.fromDegrees(longitude, latitude, height);
  this.speedToNext = speedToNext; // 前往下一节点的速度m/s
  this.stayDuration = stayDuration; //停留时间
  this.height = height
  this.views = viewArr.map(view => ({
    time: Number(view.turnTime), //触发定位时间
    view: {
      heading: view.heading || 0,
      pitch: view.pitch || -30,
      roll: view.roll || 0
    }
  }));
}

// 在停留时间段添加重复样本
dynamicObject.prototype.addStaySamples = function (position, start, duration) {
  let t = 0;
  while (t <= duration) {
    const sampleTime = Cesium.JulianDate.addSeconds(start, t, new Cesium.JulianDate());
    property.addSample(sampleTime, position);
    t += 0.1; // 10Hz采样
  }
}

dynamicObject.prototype.calculateTotalTime = function (nodes) {
  return nodes.reduce((total, node, index) => {
    // 所有节点的停留时间
    total += node.stayDuration;

    // 除末节点外的飞行时间
    if (index < nodes.length - 1) {
      const nextNode = nodes[index + 1];
      const distance = this._core.getSpaceDistancem([node.position, nextNode.position], Cesium);
      total += distance / node.speedToNext;
    }
    return total;
  }, 0);
}

dynamicObject.prototype.calculateAngle = function (currentNode, nextNode) {
  const pos1 = this._core.toDegrees(currentNode.position)
  const pos2 = this._core.toDegrees(nextNode.position)

  const heading = this._core.TwoPointAzimuth(pos1.lon, pos1.lat, pos2.lon, pos2.lat);

  // 规范化角度到-180~180范围
  const normalizedHeading = ((heading % 360) + 360) % 360;
  const adjustHeading = normalizedHeading > 180 ? normalizedHeading - 360 : normalizedHeading;
  return adjustHeading
}

//时间监测
dynamicObject.prototype.addTickListener = function () {
  const self = this;
  this._viewer.clock.onTick.addEventListener(function (clock) {
    self.handleTick(clock);
  });
};

dynamicObject.prototype.handleTick = function (clock) {
  const currentTime = clock.currentTime;
  this.getNodesInfo(currentTime)
  if (entityModel) {
    const dronePosition = entityModel.position.getValue(currentTime);

    this._viewEvents.forEach((event) => {
      if (!event.triggered && Cesium.JulianDate.compare(currentTime, event.time) >= 0) {
        console.log('停留修改视角', event);
        EventBus.$emit('changeNodeCamera', event.view)
        // 进入停留阶段，锁定视角
        this._isInStayPhase = true;
        if (entityhd.mode === 0) {
          this._viewer.trackedEntity = null
        }
        this.setCameraView(event.view, dronePosition);
        event.triggered = true;

        // 停留结束后恢复自动视角
        const stayDuration = event.duration - event.stayTime; // 假设停留时间从事件中获取
        const checkStayEnd = () => {
          return new Promise((resolve) => {
            const interval = setInterval(() => {
              if (Cesium.JulianDate.secondsDifference(clock.currentTime, event.time) >= stayDuration) {
                clearInterval(interval);
                resolve();
              }
            }, 100);
          });
        };
        checkStayEnd().then(() => {
          this._isInStayPhase = false;
          this._viewer.scene.screenSpaceCameraController.enableRotate = true;
          if (entityhd.mode === 0) {
            this._viewer.trackedEntity = entityModel
          }
        });
      }
    });

    // 非停留阶段才执行自动视角更新
    if (!this._isInStayPhase) {
      if (changeFlyView) changeFlyView(clock.currentTime);
    }
  }

};

// 设置相机视角（平滑过渡）
dynamicObject.prototype.setCameraView = function (viewParams, dronePosition) {
  this._viewer.camera.flyTo({
    destination: dronePosition,
    orientation: {
      heading: Cesium.Math.toRadians(viewParams.heading),
      pitch: Cesium.Math.toRadians(viewParams.pitch),
      roll: viewParams.roll
    },
    duration: 0.5, // 过渡时间
    maximimHeight: 10000,
    easingFunction: Cesium.EasingFunction.QUADRATIC_IN_OUT
  });
};

//获取停留阶段节点属性
dynamicObject.prototype.getNodesInfo = function (currentTime) {
  this._isInStayPhase = false;
  let currentNode = null;
  EventBus.$emit('changeAttributePopup', this._isInStayPhase)
  // 遍历所有节点，检查当前时间是否处于停留阶段
  this._nodes.forEach((node, index) => {
    if (node.stayDuration > 0 && Cesium.JulianDate.compare(currentTime, node.stayStartTime) >= 0 && Cesium.JulianDate.compare(currentTime, node.stayEndTime) <= 0) {
      this._isInStayPhase = true;
      currentNode = node;
      currentNode.Number = index + 1
    }
  });

  // 若处于停留阶段，触发信息展示
  if (this._isInStayPhase && currentNode) {
    const cartographic = Cesium.Cartographic.fromCartesian(currentNode.position);
    const nodeInfo = {
      type: "stay",
      nodeNumber: currentNode.Number,
      longitude: Cesium.Math.toDegrees(cartographic.longitude),
      latitude: Cesium.Math.toDegrees(cartographic.latitude),
      height: cartographic.height,
      duration: currentNode.stayDuration,
      speed: currentNode.speedToNext,
      views: currentNode.views
    };
    EventBus.$emit('changeNodeinfo', nodeInfo)
    EventBus.$emit('changeAttributePopup', true)
    // console.log('停留', nodeInfo);
  }
}

// var hpr = new Cesium.HeadingPitchRoll();
var flyPosition
// var Quaternion = new Cesium.Quaternion();
// var _heading = 0;
var entitymodels = null

//改变视角
var changeFlyView

function getHeading(time) {
  wheelAngle = AngleProperty.getValue(time)
  entityhd.heading = wheelAngle
}

function getFlyPosition(position) {
  var cartographic = Cesium.Cartographic.fromCartesian(position)
  var lon = Cesium.Math.toDegrees(cartographic.longitude)
  var lat = Cesium.Math.toDegrees(cartographic.latitude)
  let positionsss = new Cesium.Cartographic(Cesium.Math.toRadians(lon), Cesium.Math.toRadians(lat));
  let height = window.Viewer.scene.sampleHeight(positionsss)
  return Cesium.Cartesian3.fromDegrees(lon, lat, cartographic.height + entityhd.cameraHeight);
  // if (height && height > cartographic.height) {
  //   return Cesium.Cartesian3.fromDegrees(lon, lat, height + entityhd.cameraHeight);
  // } else {
  //   return Cesium.Cartesian3.fromDegrees(lon, lat, cartographic.height + entityhd.cameraHeight);
  // }
}

/**
 * 显示点
 */
dynamicObject.prototype.showPoint = function (isShow) {
  entityModel && entityModel.point && (entityModel.point.show = isShow)
}

/**
 * 显示线
 */
dynamicObject.prototype.showLine = function (isShow) {
  entityFly && entityFly.polyline && (entityFly.polyline.show = isShow)
}

/**
 * 显示模型
 */
dynamicObject.prototype.showModel = function (isShow) {
  entityModel && entityModel.model && (entityModel.model.show = isShow);
}

//飞行高度
dynamicObject.prototype.setFlyHeight = function (height) {
  entityhd.cameraHeight = height;
}

//飞行距离
dynamicObject.prototype.setFlyDistance = function (distance) {
  entityhd.range = distance;
}

//飞行俯仰角
dynamicObject.prototype.setFlyPitch = function (pitch) {
  entityhd.pitch = pitch;
}

//飞行模式
dynamicObject.prototype.changeFlyMode = function (index) {
  var _this = this;
  entityhd.mode = index
  switch (index) {
    case 0:
      changeFlyView = function () {

      };
      _this.BindingModel(true);
      break;
    case 1:
      this.BindingModel(false);
      changeFlyView = function (time) {
        getHeading(time);
        _this.exeuteVisualAngle(Cesium.Math.toRadians(entityhd.heading), Cesium.Math.toRadians(entityhd.pitch), entityhd.range);
      };
      break;
    case 2:
      this.BindingModel(false);
      changeFlyView = function (time) {
        getHeading(time);
        flyPosition = _this._entityFly.position.getValue(_this._viewer.clock.currentTime);
        if (!flyPosition) return;
        flyPosition = getFlyPosition(flyPosition);
        _this._viewer.camera.setView({
          destination: flyPosition,
          orientation: {
            heading: Cesium.Math.toRadians(entityhd.heading),
            pitch: Cesium.Math.toRadians(-90),
            roll: 0.0
          }
        });
      };
      break;

    case 3: // 无人机第一人称模式
      this.BindingModel(false);
      changeFlyView = function (time) {
        if (_this._isInStayPhase) return; // 停留阶段跳过自动视角更新
        getHeading(time);
        // 获取当前视角参数
        const roll = entityModel.orientation.getValue(time) ? entityModel.orientation.getValue(time).roll : 0
        const heading = entityhd.heading ? entityhd.heading : 0
        const currentView = {
          heading: Cesium.Math.toRadians(heading),
          pitch: Cesium.Math.toRadians(entityhd.pitch),
          roll: roll // 获取模型当前 roll 值
        };
        _this.exeuteView(currentView, entityhd.range);

      }
      break
  }
}

/**
 * 加速
 */
dynamicObject.prototype.faster = function () {
  this._viewer.animation.viewModel.faster()
}

/**
 * 减速meraHeight
 */
dynamicObject.prototype.slower = function () {
  // 倍率减
  this._viewer.animation.viewModel.slower()
}

/**
 * 设置倍数
 */
dynamicObject.prototype.setMultiplier = function (multiplier) {
  this._viewer.clock.multiplier = parseFloat(multiplier);
}

/**
 * 是否暂停
 */
dynamicObject.prototype.isPause = function (isPause) {
  var clockViewModel = this._viewer.clockViewModel;
  clockViewModel.shouldAnimate = !isPause;
}
/**
 * 结束飞行
 */
dynamicObject.prototype.exit = function () {
  this.isPause(true);
  this._viewer.clock.multiplier = 1;
  this.executeSignout();
  this.BindingModel(false);
  this._viewer.entities.remove(entityFly);
  this._viewer.entities.remove(entityModel);
  this._viewer.scene.primitives.remove(this._axises._prim);
  entityFly = null;
  entityModel = null;
  this._entityFly = null;
  if (this.item) {
    this.item.show = true

  }
  maxNum = 0
  // this.setItemPosition()
}
dynamicObject.prototype.removeItem = function () {
  this._viewer.entities.remove(this.item)
  this.item = null
}

//lable回调函数
dynamicObject.prototype.updateSpeedLabel = function (time, result) {
  //if (fun && typeof fun === 'function') {
  //    fun(_this._entityFly);
  //}
  //this.entityhd = {
  //    start: null,
  //    time: null
  //};
  //this.entityhd.time = time;
  //if (this.fun != null && typeof fun === 'function') {
  //    fun(_this._entityFly);
  //}
  //return "";
}

//添加时间位置样本
dynamicObject.prototype.computeCirclularFlight = function (position) {
  var _this = this;
  velocityVectorProperty = new Cesium.VelocityVectorProperty(property, false);
  var _time, time, _position, _position1;
  for (var i = 0; i < position.length; i++) {
    if (i === 0) {
      //起点
      time = Cesium.JulianDate.addSeconds(entityhd.start, 0, new Cesium.JulianDate());
      _position = Cesium.Cartesian3.fromDegrees(position[0].x, position[0].y, Cesium.defaultValue(entityhd.lineHeight, position[i].z));

      property.addSample(time, _position);
      //计算两点方位角
      wheelAngle = _this._core.TwoPointAzimuth(position[0].x, position[0].y, position[1].x, position[1].y);
      AngleProperty.addSample(time, wheelAngle);
    }
    try {
      if (i > 0) {
        _position = new Cesium.Cartesian3(property._property._values[i * 3 - 3], property._property._values[i * 3 - 2], property._property._values[i * 3 - 1]);
        _position1 = Cesium.Cartesian3.fromDegrees(position[i].x, position[i].y, Cesium.defaultValue(entityhd.lineHeight, position[i].z));

        var long = Cesium.Cartesian3.distance(_position, _position1);
        time = Cesium.JulianDate.addSeconds(property._property._times[i - 1], 0.5, new Cesium.JulianDate());
        _time = Cesium.JulianDate.addSeconds(property._property._times[i - 1], long / entityhd.speed, new Cesium.JulianDate());

        property.addSample(_time, _position1);
        //计算两点方位角
        wheelAngle = _this._core.TwoPointAzimuth(position[i - 1].x, position[i - 1].y, position[i].x, position[i].y);
        const norm = ((wheelAngle % 360) + 360) % 360
        wheelAngle = wheelAngle > 180 ? norm - 360 : wheelAngle
        AngleProperty.addSample(time, wheelAngle);
        AngleProperty.addSample(_time, wheelAngle);
      }
    } catch (e) {
      console.log(e);
    }
  }
  console.log("property", property)
  return property;
}



/**
 * 暂停浏览
 */
dynamicObject.prototype.executePauseFly3DPaths = function () {
  var clockViewModel = this._viewer.clockViewModel
  if (clockViewModel.shouldAnimate) {
    clockViewModel.shouldAnimate = false
  } else if (this._viewer.clockViewModel.canAnimate) {
    clockViewModel.shouldAnimate = true
  }
}

/**
 * 添加对象
 */
dynamicObject.prototype.changeModel = function (url) {
  entityModel.model.uri = url;
}

//浏览方式飞向视点
/**
 * 获取视野点
 */
dynamicObject.prototype.PointView = function () {
  var originalCameraLocation = {
    position: Viewer.camera.position.clone(),
    orientation: {
      heading: Viewer.camera.heading,
      pitch: Viewer.camera.pitch,
      roll: Viewer.camera.roll,
    }
  };
  return originalCameraLocation;
}

/**
 * 开始浏览。
 * @param {Paths}
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.PlayPaths = function (Paths) {
  var that = this;
  setInterval(function () {
    viewer.camera.setView({
      // Cesium的坐标是以地心为原点，一向指向南美洲，一向指向亚洲，一向指向北极州
      // fromDegrees()方法，将经纬度和高程转换为世界坐标
      destination: Cesium.Cartesian3.fromDegrees(117.48, 30.67, 15000.0),
      orientation: {
        // 指向
        heading: Cesium.Math.toRadians(90, 0),
        // 视角
        pitch: Cesium.Math.toRadians(-90),
        roll: 0.0
      }
    });
  }, 2000);
}

/**
 * 绑定模型
 * @param {binding} 是否绑定。
 */
dynamicObject.prototype.BindingModel = function (binding) {
  if (binding) {
    this._viewer.trackedEntity = entityModel;
  } else {
    this._viewer.trackedEntity = undefined;
    this._viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
  }
}

/**
 * 改变视角
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.exeuteVisualAngle = function (viewHeading, viewPitch, viewRange) {
  var hpRange = {
    heading: null,
    pitch: null,
    range: null
  };
  hpRange.heading = viewHeading || Cesium.Math.toRadians(90);
  hpRange.pitch = viewPitch || Cesium.Math.toRadians(0);
  hpRange.range = viewRange || 1000;
  var center = this._entityFly.position.getValue(this._viewer.clock.currentTime);
  if (!center) return;
  center = getFlyPosition(center);

  var hpRanges = new Cesium.HeadingPitchRange(hpRange.heading, hpRange.pitch, hpRange.range);
  //if (center) this._viewer.camera.lookAt(center, hpRange);
  var clockViewModel = this._viewer.clockViewModel;
  if (clockViewModel.shouldAnimate) {
    this._viewer.camera.lookAt(center, hpRanges);
  }
}

/**
 * 改变无人机视角
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.exeuteView = function (viewParams, viewRange) {
  var hpRange = {
    heading: viewParams.heading || Cesium.Math.toRadians(90),
    pitch: viewParams.pitch || Cesium.Math.toRadians(-30),
    roll: viewParams.roll || 0,
    range: viewRange || 0
  };
  var center = entityModel.position.getValue(this._viewer.clock.currentTime);
  if (!center) return;
  center = getFlyPosition(center);

  var clockViewModel = this._viewer.clockViewModel;
  if (clockViewModel.shouldAnimate) {
    this._viewer.camera.setView({
      destination: center,
      orientation: {
        heading: hpRange.heading,
        pitch: hpRange.pitch,
        roll: hpRange.roll
      }
    });
  }
}

/**
 * 是否显示路线
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.Pathshow = function (route) {
  this._entityFly.polyline.show = route
}

/**
 * 是否显示点
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.Pointshow = function (route) {
  entityModel._point.show = route
}

/**
 * 是否显示模型
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.Modelshow = function (route) {
  entityModel._model.show = route
}

/**
 * 向前飞行漫游路径
 * @returns {Object} 返回一个json对象。
 */
dynamicObject.prototype.executePlayForwardFly3DPaths = function () {
  var clockViewModel = this._viewer.clockViewModel
  var multiplier = clockViewModel.multiplier
  if (multiplier < 0) {
    clockViewModel.multiplier = -multiplier
  }
  clockViewModel.shouldAnimate = true
}

/**
 * 向后飞行漫游路径
 */
dynamicObject.prototype.executePlayReverseFly3DPaths = function () {
  var clockViewModel = this._viewer.clockViewModel
  var multiplier = clockViewModel.multiplier
  if (multiplier > 0) {
    clockViewModel.multiplier = -multiplier
  }
  clockViewModel.shouldAnimate = true
}

/**
 * 退出飞行漫游路径
 */
dynamicObject.prototype.executeSignout = function () {
  var start = Cesium.JulianDate.fromDate(new Date())
  this._viewer.clock.startTime = start.clone()
  var stop = Cesium.JulianDate.addSeconds(start, 86400, new Cesium.JulianDate())
  this._viewer.clock.stopTime = stop.clone()
  //this.Viewer.entities.remove(this.entityFly);
  EventBus.$emit('changeJudstModel', false)
}

/**
 * 结束当前操作
 */
dynamicObject.prototype.forceEndHanlder = function () {
  if (this.handler) {
    this.handler.destroy()
    this.handler = undefined
  }
}

dynamicObject.prototype.onTicks = function (viewer) {
  viewer.clock.onTick.addEventListener(function () {
    viewer.scene.screenSpaceCameraController.enableTilt = false
    // if (viewer.camera.pitch > 0) {

    // }
  })
}

/**
 * 实时修改路径坐标
 * @param {*} positions 
 */
dynamicObject.prototype.setItemPosition = function (positions) {
  var _update = function () {
    return positions;
  };
  this.item.show = true
  this.item.polyline.positions = new Cesium.CallbackProperty(_update, false);

}

/**
 * 获取路径长度
 * @param {*} positions 
 * @returns 
 */

dynamicObject.prototype.getDistance = function (positions) {
  return this._core.getSpaceDistancem(positions, Cesium)

}

/**
 * 实时修改选中的节点坐标
 * @param {*} index 
 * @param {*} cartesian 
 */

dynamicObject.prototype.setPointPosition = function (index, cartesian) {
  labelEntity[index].position = cartesian
}
dynamicObject.prototype.setAllPointPosition = function (positions) {
  for (let i = 0; i < positions.length; i++) {
    labelEntity[i].position = positions[i]
    labelEntity
  }
  this.ploylinejl.positions = positions
}

dynamicObject.prototype.setPoint = function (position, posData) {
  maxNum = 0
  this.removePoint()
  for (let i = 0; i < position.length; i++) {
    maxNum = maxNum + 1
    labelEntity.push(
      this._viewer.entities.add({
        position: position[i],
        point: {

        },
        label: {
          text: maxNum.toString(),
          pixelOffset: new Cesium.Cartesian2(20, -20),
          font: "16px sans-serif"
        },
        billboard: {
          image: this._pointIcon,
          width: 28,
          height: 28,
          pixelOffset: new Cesium.Cartesian2(0, -20)
        },
        properties: posData[i].properties
      })
    )
  }

  this.ploylinejl.positions = position

  // this.setItemPosition(this.ploylinejl.positions)
}





/**
 * 删除选中的点的
 * @param {*} index 
 */

dynamicObject.prototype.deletePointItem = function (index) {
  this._viewer.entities.remove(labelEntity[index])

  labelEntity.splice(index, 1)
  this.ploylinejl.positions.splice(index, 1)
}

dynamicObject.prototype.addPointItem = function (cartesian) {
  // let num = parseInt(labelEntity[labelEntity.length - 1].label.text._value)
  maxNum = maxNum + 1
  labelEntity.push(this._viewer.entities.add({
    position: cartesian,
    point: {

    },
    label: {
      text: maxNum.toString(),
      pixelOffset: new Cesium.Cartesian2(20, -20),
      font: "16px sans-serif"
    },
    billboard: {
      image: this._pointIcon,
      width: 28,
      height: 28,
      pixelOffset: new Cesium.Cartesian2(0, -20)

    },
    properties: {
      Number: maxNum.toString(),
      hoveringtime: 0,
      angle: 0,
      flightHs: 0,
      speed: 0,
      postureList: []
    }


  }))
  this.ploylinejl.positions.push(cartesian)
}

dynamicObject.prototype.removePoint = function () {
  labelEntity.forEach((item) => {
    this._viewer.entities.remove(item)

  })

  labelEntity = []
}

export default dynamicObject
